package com.wholesmart.common.security.authentication;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wholesmart.common.bean.Message;
import com.wholesmart.common.enums.SystemStatusEnum;

/**
 * Spring Security鉴权失败后的处理器
 * <p>
 * 当对用户进行登录授权时，如果授权失败就会交由该类处理。
 * <p>
 * 主要用于接收鉴权信息，然后自定义返回前端的Json消息，当然你也可以在这里根据需求做页面跳转。
 * <p>
 * 需要手动配置到WebSecurityConfigurerAdapter的实现内中。
 * 
 * @author dyw
 * @date 2019年10月11日
 */
@Component("wholesmartAuthenticationFailureHandler")
public class WholesmartAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	private Logger logger = LoggerFactory.getLogger(getClass());
	/** Spring框架初始化后，这个类会被加载到IOC容器中，所以这里可以直接注入 */
	@Autowired
	private ObjectMapper objectMapper;

	/*
	 * AuthenticationException对象封装了我们的错误异常
	 * 
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		logger.info("登陆失败");
		// 设置服务器状态码为401
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(objectMapper.writeValueAsString(
				Message.message(SystemStatusEnum.UNAUTHORIZED.getStatue(), exception.getMessage(), null)));
	}
}
